<template>
<div class="list">

    <Drawer title="配置" :closable="false" width="540" v-model="setting" :styles="styles">
        <Form label-position="top">
            <FormItem label="搜索">
                <Checkbox-group v-model="filterItemChecked">
                    <Row>
                        <Col span="8" v-for="filter in filters" :key="filter.key" v-if="filter.title">
                        <Checkbox :label="filter.key">{{filter.title}}</Checkbox>
                        </Col>
                    </Row>
                </Checkbox-group>
            </FormItem>
            <FormItem label="栏目">
                <Checkbox-group v-model="tableColumnsChecked" @on-change="changeTableColumns">
                    <Row>
                        <Col span="8" v-for="column in columns" :key="column.key" v-if="column.title">
                        <Checkbox :label="column.key">{{column.title}}</Checkbox>
                        </Col>
                    </Row>
                </Checkbox-group>
            </FormItem>
        </Form>
        <div class="demo-drawer-footer">
            <Button style="margin-right: 8px" @click="setting = false">取消</Button>
            <Button type="primary" @click="setting = false">保存</Button>
        </div>
    </Drawer>

    <Collapse accordion class="search" value="1" @on-change="setTableHeight" v-if="filters" ref="filters">
        <Panel name="1">
            搜索
            <template slot="content">
                <Row :gutter="16" type="flex" style="margin-bottom: -20px;" v-if="isShowFilters">
                    <Col v-for="filter in filters" :key="filter.key" :span="getFilterCol(filter.col)" style="margin-bottom: 20px;" v-if="filterItemChecked.includes(filter.key)">
                    <label class="ivu-form-item-label">{{filter.title}}</label>
                    <div class="ivu-form-item-content">
                        <FieldRender :field="filter" :fieldModel="filterItem" :ref="filter.key" :debounceTime="800"></FieldRender>
                    </div>
                    </Col>
                </Row>
            </template>
        </Panel>
    </Collapse>

    <div class="table">
        <Table :data="data" :columns="columnsList" v-bind="$attrs" v-on="$listeners" :border="border" :loading="loading" stripe ref="table" :height="height" size="small">

            <div slot="footer" style="padding: 0px 10px;">
                <Page :total="total" v-if="isPage" show-sizer :current="page" :page-size="rows" :page-size-opts="[10,20,50,100,500]" @on-change="changePage" @on-page-size-change="changePageSize" style="float: left;"></Page>
                <Divider type="vertical" v-if="isPage" />
                <span>共 <b>{{total}}</b> 条</span>
                <div class="tool" style="float: right;">
                    <Tooltip content="刷新">
                        <Button type="text" @click="loadData" size="small">
                            <Icon type="ios-loading" size="20" />
                        </Button>
                    </Tooltip>
                    <Divider type="vertical" v-if="isSetting" />
                    <Tooltip content="设置" placement="top" v-if="isSetting">
                        <Button type="text" @click="setting = true" size="small">
                            <Icon type="md-settings" size="20" />
                        </Button>
                    </Tooltip>
                </div>
            </div>

        </Table>
    </div>

</div>
</template>

<script>
import {
    initField
} from '@/utils/tool.js'

export default {
    inject: ["layoutSize"],
    props: {
        columns: Array,
        filters: Array,
        /**全屏显示 是否计算高度 */
        fit: {
            type: Boolean,
            default: true
        },
        /**每页显示记录数 */
        size: {
            type: Number,
            default: 20
        },
        border: {
            type: Boolean,
            default: true
        },
        isSetting: {
            type: Boolean,
            default: true
        },
        format: {
            type: Function
        }
    },
    data() {
        return {
            total: 0,
            data: [],
            loading: true,
            height: 0,
            setting: false,
            columnsList: [],
            tableColumnsChecked: [],
            filterItem: {},
            filterItemChecked: [],
            buttonSize: 'large',
            page: 1,
            rows: this.size,
            isShowFilters: true,
            styles: {
                height: 'calc(100% - 55px)',
                overflow: 'auto',
                paddingBottom: '53px',
                position: 'static'
            },
            isPage: true
        }
    },
    watch: {
        filterItem: {
            handler: function (val, oldVal) {
                this.page = 1
                this.loadData()
            },
            deep: true
        },
        layoutSize: {
            handler: function (val, oldVal) {
                this.setTableHeight()
            },
            deep: true,
            immediate: true
        }
    },
    
    methods: {
        async loadData(page) {
            this.loading = true

            let _filterItem = JSON.parse(JSON.stringify(this.filterItem).replace(/\[|\]/g, '"'))

            if(page) this.page = page
            let params = Object.assign({}, {
                page: this.page
            }, {
                rows: this.rows
            }, _filterItem)

            this.$emit('on-before-load', params)

            let res = await this.$attrs.loadData(params)
            if (res.isSucceed) {
                if (this.format) {
                    this.data = this.format(res.rows)
                } else {
                    this.data = res.rows
                }

                this.total = res.total

                this.isPage = this.total && this.total > this.size

                this.$emit('on-after-load', this.data)
            } else {
                console.error(res.message)
            }

            this.loading = false
        },
        changePage(page) {
            this.page = page
            this.loadData();
        },
        changePageSize(pageSize) {
            this.rows = pageSize
            this.loadData();
        },
        changeTableColumns() {
            this.columnsList = this.columns.concat()

            this.columns.map(column => {
                if (!column.type && !this.tableColumnsChecked.includes(column.key)) {
                    let i = this.columnsList.findIndex(item => item.key == column.key)
                    this.columnsList.splice(i, 1)
                }
            })
        },
        filterReset() {
            for (let index in this.filters) {
                let models = this.filters[index].models
                initField(this.filterItem, models)
            }
        },
        setTableHeight() {
            if (this.fit) {
                let self = this
                this.$nextTick(function () {
                    self.height = self.layoutSize.height

                    let searchDom = document.querySelector(".search")
                    if (searchDom) {
                        setTimeout(function () {
                            let searchHeight = searchDom ? searchDom.offsetHeight + 5 : 0

                            self.height -= searchHeight + 1
                        }, 0)
                    }
                })
            } else {
                this.height = this.$attrs.height ? this.$attrs.height : 400
            }
        },
        getFilterCol(col){
            return col || 8
        }
    },
    created() {
        this.columns.unshift({
            type: 'index',
            title: "序号",
            width: 65,
            align: 'center',
            fixed: 'left',
        }, {
            type: 'selection',
            width: 60,
            align: 'center',
            fixed: 'left',
        })

        let action = this.columns[this.columns.length - 1]
        if (action.key == "action") {
            action.fixed = "right"
            action.align = "center"
        }
    },
    mounted() {
        //table页头控制
        for (let index in this.columns) {
            if (!this.columns[index].type) {
                this.tableColumnsChecked.push(this.columns[index].key)
            }
        }
        this.changeTableColumns()

        //搜索项控制
        for (let index in this.filters) {
            this.filterItemChecked.push(this.filters[index].key)
        }

        if (this.filters) {
            //创建搜索model
            for (let index in this.filters) {
                let models = this.filters[index].models
                initField(this.filterItem, models)
            }
        } else {
            //加载数据
            this.loadData();
        }
    }
}
</script>

<style lang="less" scoped>
.demo-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
}

.list {
    height: 100%;

    .noExpand {
        /deep/ .ivu-collapse-header {
            display: none;
        }
    }

    .search {
        border-radius: 0px;
        margin-bottom: 5px;

        .ivu-form-item-content {
            height: 32px;
        }
    }

    .table {
        overflow: hidden;
        background-color: #FFF;
        width: 100%;
    }

    .footer {
        background-color: #FFF;
        overflow: hidden;
        height: 50px;
        position: fixed;
        bottom: 0px;
        width: 100%;
        box-shadow: 0px -2px 2px rgba(0, 0, 0, .07);
        z-index: 999;
        left: 0px;
    }

    /deep/ .ivu-page .ivu-page-options {
        margin-top: -3px;
    }
}
</style>
